#pragma once
#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/stat.h>
#include<cstdio>
#include<cerrno>
#include<unistd.h>
#include<fcntl.h>

const std::string comm_fifopath="./myfifo";
#define Create 1
#define User   2
#define DefultFd -1
#define Read  O_RDONLY
#define Write O_WRONLY
#define BaseSize 4096

class NamedPipe
{
private:
    bool OpenNamePipe(int mode)
    {
        _fd=open(_fifo_path.c_str(),mode);
        if(_fd<0)
        {
            return false;
        }
        return true;
    }
public:
    NamedPipe(const std::string &path,int who)
    :_fifo_path(path),_id(who),_fd(DefultFd)
    {
        if(_id==Create)
        {
            int res=mkfifo(_fifo_path.c_str(),0666);
            if(res!=0)
            {
                perror("mkfifo");
            }
            std::cout<<"create"<<std::endl;
        }
    }

    ~NamedPipe()
    {
        sleep(5);
        if(_id==Create)
        {
            int res=unlink(_fifo_path.c_str());
            if(res!=0)
            {
                perror("mkfifo");
            }
        }
        if(_fd!=DefultFd)close(_fd);
        std::cout<<"free"<<std::endl;
    }
    bool OpenRead()
    {
        return OpenNamePipe(Read);
    }

    bool OpenWrite()
    {
        return OpenNamePipe(Write);
    }
    int ReadNamePipe(std::string *buff)
    {
        char buf[BaseSize];
        int n=read(_fd,buf,sizeof(buf));
        if(n>0)
        {
            buf[n]='\0';
            *buff=buf;
        }

        return n;
    }
    int WriteNamePipe(const std::string &in)
    {
        return write(_fd,in.c_str(),in.size());
    }


    

private:
    std::string _fifo_path;
    int _id;
    int _fd;
};

